package com.lnsoft.dqfs.server.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class DqfsDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${project.is_super}")
    private String isSuper;


    /**
     * 根据客户端2个字节标识 与 端口号 获取客户端ID
     *
     * @param clientName
     * @param port
     * @return
     */
    public String getIacmId(int clientName, int port) {
        String sql = "SELECT ID FROM T_DQFS_IACM WHERE ZDYZDTXDZ=? AND ZZDK=? AND SFFQ in (0,3)";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, clientName, port);
        if (list == null || list.size() != 1) {
            return null;
        }
        return list.get(0).get("id").toString();
    }

    /**
     * 更新最新离线时间 (用于判断是否在线)
     *
     * @param clientId
     */
    public void updateIacmDownTime(String clientId) {
        String sql = "UPDATE T_DQFS_IACM SET ZXLXSJ=SYSDATE WHERE ID=?";
        jdbcTemplate.update(sql,  clientId);
    }

    /**
     * 批量添加或更新主动上传数据
     * id规则： clientName-port-cjsj
     */
    public void saveYcList(final int clientName, final int port, final String clientId, final List<Yc> list) {
        String sql = "MERGE INTO T_DQFS_YC T1 USING (SELECT ? AS PK_ID FROM DUAL) T2 ON (T1.ID=T2.PK_ID) " +
                "WHEN MATCHED THEN " +
                "UPDATE SET RKSJ=SYSDATE " +
                "WHEN NOT MATCHED THEN " +
                "INSERT (ID,SBID,TYNDY,DCDY,JXWD,JXSD,GPRS,HJWD,HJSD,ZNDL,CUDL,ALDL,FEDL,CJSJ,SOND,YF,BY1,BY2,BY3) " +
                "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,TO_DATE(?,'YYYY-MM-DD HH24:MI:SS'),?,?,?,?,?)";

        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int index) throws SQLException {
                Yc yc = list.get(index);
                String id = clientName + "" + port + yc.getCjsj();
                ps.setString(1, id);
                ps.setString(2, id);
                ps.setString(3, clientId);
                ps.setFloat(4,yc.getTyndy());
                ps.setFloat(5,yc.getDcdy());
                ps.setFloat(6,yc.getJxwd());
                ps.setFloat(7,yc.getJxsd());
                ps.setFloat(8,yc.getGprs());
                ps.setFloat(9,yc.getHjwd());
                ps.setFloat(10,yc.getHjsd());
                ps.setFloat(11,yc.getZndl());
                ps.setFloat(12,yc.getCudl());
                ps.setFloat(13,yc.getAldl());
                ps.setFloat(14,yc.getFedl());
                ps.setString(15,yc.getCjsj());
                ps.setFloat(16,yc.getSond());
                ps.setFloat(17,yc.getYf());
                ps.setFloat(18,yc.getBy1());
                ps.setFloat(19,yc.getBy2());
                ps.setFloat(20,yc.getBy3());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });

    }

    public Map<String, Object> getSjjlByClientId(String clientId){
        String sql = "SELECT * FROM T_DQFS_SJJL WHERE SJJQ=0 AND SBID=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, clientId);
        if(list!=null && list.size()==1){
            return list.get(0);
        }
        return null;

    }

    /**
     *  当前终端是否有更新参数操作
     * @param clientId
     * @return
     */
    public ConnectArg getConnectArg(String clientId){
       // List<ConnectArg> list = new ArrayList<>();
//        if("ff8080816676b36a01667b6ed28b0008".equals(clientId)){
//            ConnectArg connectArg = ConnectArg.builder().connectArress(1).ip("192.168.10.20").port(4038).build();
//            return connectArg;
//        }
        String sql = "SELECT ID,UP_ARGS FROM T_DQFS_UPARG WHERE IS_SUPER=? AND IACM_ID=? AND TYPE=0";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, isSuper, clientId);
        if(list!=null && list.size()>0){
            Map<String, Object> map = list.get(0);
            String id = (String)map.get("ID");
            String upArgs = (String)map.get("UP_ARGS");
            return ConnectArg.builder().argId(id).upArgs(upArgs).build();
        }
        return null;
    }

    /**
     * 当前参数更新成功 修改数据库数据
     * @param argId
     */
    public void updateConnectArg(String argId){
        String sql = "UPDATE T_DQFS_UPARG SET TYPE=1,UP_TIME=SYSDATE WHERE ID=?";
        jdbcTemplate.update(sql,argId);
    }

    /**
     * 查询终端是否对数据加密
     *
     * @param clientId 终端在数据库中的主键ID
     * @return true 表示存在；false 表示不存在；
     */
    public boolean hasEncrypted(String clientId) {
        String sql = "SELECT ID,SBID,SBBH,JMZT FROM T_DQFS_IACD_JM WHERE SBID=? AND JMZT=1";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, clientId);
        if(list != null && list.size() == 1){
            return true;
        }
        return false;
    }

    /**
     * 查询终端是否对数据加密
     *
     * @param clientId 终端在数据库中的主键ID
     * @return true 表示存在；false 表示不存在；
     */
    public Map<String,Object> getVersion(String clientId) {
        String sql = "SELECT ID,SJBBH FROM T_DQFS_SJJL WHERE SBID=? AND SJJG=0 ORDER BY CJRQ DESC ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, clientId);
        if(list != null && list.size() >= 1){
            return list.get(0);
        }
        return null;
    }

    /**
     * 更新最新离线时间 (用于判断是否在线)
     *
     * @param recordId 数据库记录id
     * @param date 升级日期
     * @param result 升级结果
     * @param oldVersion 升级前版本号
     */
    public void updateIacmUpgradeResult(String recordId, String date, int result, String oldVersion,String note) {
        String sql = "UPDATE T_DQFS_SJJL SET SJRQ=?,SJJG=?,SBDQBBH=?,BZ=? WHERE ID=?";
        jdbcTemplate.update(sql,  date,result,oldVersion, note,recordId);
    }

}
